package gameClient.thread;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import gameClient.model.Player;
import gameClient.model.Poker;
import gameClient.view.ClientMainFrame;

/**
 * 接收消息的线程，对服务器发来的消息进行处理
 */
public class ReceiveThread extends Thread {
    //指定客户端与服务端通信Socket
    public Socket socket;
    //客户端主窗体，在客户端显示扑克牌
    public ClientMainFrame clientMainFrame;

    //进展步骤
    private int step = 0;
    //运行状态
    private boolean isRun = true;

    public boolean isRun() {
        return isRun;
    }

    public void setRun(boolean run) {
        isRun = run;
    }

    public ReceiveThread(Socket socket, ClientMainFrame clientMainFrame) {
        this.socket = socket;
        this.clientMainFrame = clientMainFrame;
    }

    //客户端处理服务器端处理消息的线程体
    @Override
    public void run() {
        try {
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());

            while (true) {
                if (!isRun) {
                    break;
                }
                //取服务器发来的消息
                String jsonString = dataInputStream.readUTF();
                System.out.println("客户端JSON串：" + jsonString);

                if (step == 0) {
                    //玩家列表
                    List<Player> players = new ArrayList<>();

                    //解析JSON字符串并取玩家信息，封装成对象数据，在客户端主窗体显示
                    JSONArray playerJsonArray = JSONArray.parseArray(jsonString);
                    for (int i = 0; i < playerJsonArray.size(); i++) {
                        JSONObject playerJsonObject = playerJsonArray.getJSONObject(i);
                        //从jsonObject取出玩家信息
                        int id = playerJsonObject.getInteger("id");
                        String name = playerJsonObject.getString("name");
                        JSONArray pokerJsonArray = playerJsonObject.getJSONArray("pokers");
                        // 玩家扑克列表
                        List<Poker> pokers = new ArrayList<>();

                        //从pokerJsonArray获取每张扑克信息
                        for (int j = 0; j < pokerJsonArray.size(); j++) {
                            JSONObject pokerJsonObject = pokerJsonArray.getJSONObject(j);
                            int pokerId = pokerJsonObject.getInteger("id");
                            String pokerName = pokerJsonObject.getString("name");
                            int pokerNum = pokerJsonObject.getInteger("num");
                            Poker poker = new Poker(pokerId, pokerName, pokerNum);
                            pokers.add(poker);
                        }
                        //封装完整的玩家信息
                        Player player = new Player(id, name, pokers);
                        players.add(player);
                    }
                    System.out.println("玩家人数：" + players.size());
                    System.out.println("玩家信息：" + players);
                    //把玩家所持扑克牌显示到主窗体
                    if (players.size() == 3) {
                        clientMainFrame.showAllPlayersInfo(players);
                        step = 1;
                    }
                } else if (step == 1) {
                    //接收抢地主/出牌消息
                    JSONObject msgJsonObject = JSONObject.parseObject(jsonString);
                    //解析
                    int typeid = msgJsonObject.getInteger("typeid");
                    int playerid = msgJsonObject.getInteger("playerid");
                    String content = msgJsonObject.getString("content");
                    //判断消息类型
                    if (typeid == 1) {
                        //消息类型为不抢，显示不抢的信息
                        clientMainFrame.showMessage(playerid, 1);
                        //设置下家开始抢地主
                        if (playerid + 1 == clientMainFrame.currentPlayer.getId()) {
                            clientMainFrame.getLord();
                        }
                    } else if (typeid == 2) {
                        //消息类型为抢地主
                        JSONArray pokerJsonArray = msgJsonObject.getJSONArray("pokers");
                        List<Poker> lordPokers = new ArrayList<>();
                        for (int i = 0; i < pokerJsonArray.size(); i++) {
                            JSONObject pokerJsonObject = pokerJsonArray.getJSONObject(i);
                            int pokerId = pokerJsonObject.getInteger("id");
                            String pokerName = pokerJsonObject.getString("name");
                            int pokerNum = pokerJsonObject.getInteger("num");
                            Poker poker = new Poker(pokerId, pokerName, pokerNum);
                            lordPokers.add(poker);
                        }
                        //如果是自己抢的地主
                        if (clientMainFrame.currentPlayer.getId() == playerid) {
                            //添加地主牌
                            clientMainFrame.addLordPokers(lordPokers);
                            //显示出牌按钮
                            clientMainFrame.showChuPaiLabel();
                        }
                        //显示地主图标
                        clientMainFrame.showLordIcon(playerid);
                        //隐藏消息框
                        clientMainFrame.messageLabel.setVisible(false);
                        //可选择出牌列表
                        clientMainFrame.addClickEventToPoker();

                    } else if (typeid == 3) {
                        //显示不出牌信息
                        clientMainFrame.showMessage(playerid, 3);
                        //如果自己是下家，显示出牌按钮
                        if ((playerid + 1) % 3 == clientMainFrame.currentPlayer.getId()) {
                            clientMainFrame.showChuPaiLabel();
                        }
                    } else if (typeid == 4) {
                        //出牌消息
                        //获取出牌列表
                        JSONArray pokersJsonArray = msgJsonObject.getJSONArray("pokers");
                        List<Poker> pokers = new ArrayList<>();
                        for (int i = 0; i < pokersJsonArray.size(); i++) {
                            JSONObject pokerJsonObject = pokersJsonArray.getJSONObject(i);
                            int pokerId = pokerJsonObject.getInteger("id");
                            String pokerName = pokerJsonObject.getString("name");
                            int pokerNum = pokerJsonObject.getInteger("num");
                            Poker poker = new Poker(pokerId, pokerName, pokerNum);
                            pokers.add(poker);
                        }

                        //显示出牌列表
                        clientMainFrame.showOutPokerList(playerid, pokers);
                        //判断玩家是否为下家并显示出牌按钮
                        if ((playerid + 1) % 3 == clientMainFrame.currentPlayer.getId()) {
                            clientMainFrame.showChuPaiLabel();
                        }
                        //记录上一个出牌玩家id
                        clientMainFrame.prevPlayerid = playerid;

                    } else if (typeid == 5) {
                        /**
                         * --重新理清这部分逻辑--
                         * 准确输出：
                         * 恭喜你，地主赢了！
                         * 恭喜你，农民赢了！
                         * 很遗憾，地主输了！
                         * 很遗憾，农民输了！
                         */
                        String finalMessage = content;

                        if(finalMessage.equals("lordWin")){
                            //地主胜利
                            if(clientMainFrame.isLord){
                                JOptionPane.showMessageDialog(clientMainFrame, "恭喜，您胜利了！");
                            }else{
                                JOptionPane.showMessageDialog(clientMainFrame, "很遗憾，你失败了");
                            }
                        }else{
                            //农民胜利
                            if(!clientMainFrame.isLord){
                                JOptionPane.showMessageDialog(clientMainFrame, "恭喜，您胜利了！");
                            }else{
                                JOptionPane.showMessageDialog(clientMainFrame, "很遗憾，你失败了");
                            }

                        }
                        clientMainFrame.gameOver();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
